<!-- 优惠券 -->
<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model="formInline.name"
          placeholder="请输入优惠券标题"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="formInline.type"
          size="mini"
          placeholder="请选择优惠券类型"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option> </el-select
      ></el-form-item>
      <el-form-item>
        <el-select
          v-model="formInline.status"
          size="mini"
          placeholder="请选择优惠券状态"
        >
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option> </el-select
      ></el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          size="mini"
          icon="el-icon-search"
          >查找</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="addopen"
          size="mini"
          icon="el-icon-edit"
          >添加</el-button
        >
        <el-button type="primary" size="mini" icon="el-icon-download"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <div class="tables">
      <template>
        <el-table border :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="优惠券ID" sortable align="center">
          </el-table-column>
          <el-table-column prop="name" label="优惠券名称" align="center">
          </el-table-column>
          <el-table-column prop="desc" label="介绍" align="center">
          </el-table-column>
          <el-table-column prop="tag" label="标签" align="center">
          </el-table-column>
          <el-table-column prop="min" label="最低消费" align="center">
            <template slot-scope="props">
              {{ "满" + props.row.min + "元可用" }}
            </template>
          </el-table-column>
          <el-table-column prop="discount" label="满减金额" align="center">
            <template slot-scope="props">
              {{ "减免" + props.row.discount + "元" }}
            </template>
          </el-table-column>
          <el-table-column prop="limit" label="每人限额" align="center">
          </el-table-column>
          <el-table-column prop="goodsType" label="商品使用范围" align="center">
            <template slot-scope="scope">
              {{ convertStatus1(scope.row.goodsType) }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="优惠券类型" align="center">
            <template slot-scope="scope">
              {{ convertStatus2(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="total" label="优惠券数量" align="center">
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              {{ convertStatus3(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
            align="center"
            width="250"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="mainopen(scope.row)"
              >
                详情
              </el-button>
              <el-button
                type="info"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="dels(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="get.page"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="get.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- ========================= -->
    <el-dialog title="创建" :visible.sync="dialogVisible" width="50%">
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-width="120px"
        label-position="left"
        style="margin-left: 50px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 300px"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input
            v-model="form.desc"
            style="width: 300px"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input
            v-model="form.tag"
            style="width: 300px"
            size="mini"
          ></el-input>
        </el-form-item>
        <el-form-item label="最低消费">
          <el-input v-model="form.min" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="满减金额">
          <el-input v-model="form.discount" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限额">
          <el-input v-model="form.limit" style="width: 300px">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="分发类型">
          <el-select v-model="form.status" size="mini">
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option> </el-select
        ></el-form-item>
        <el-form-item label="优惠券数量">
          <el-input v-model="form.total" style="width: 300px">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期">
          <el-radio-group v-model="validityType">
            <el-radio-button label="relativeDays">领券相对天数</el-radio-button>
            <el-radio-button label="absoluteTime">指定绝对时间</el-radio-button>
          </el-radio-group>

          <!-- 领券相对天数模块 -->
          <div v-if="validityType === 'relativeDays'" style="margin-top: 10px">
            <el-input v-model="form.days" style="width: 300px">
              <template slot="append">天</template>
            </el-input>
          </div>

          <!-- 指定绝对时间模块 -->
          <div v-if="validityType === 'absoluteTime'" style="margin-top: 10px">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择日期"
            ></el-date-picker>
            至
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择日期"
            ></el-date-picker>
          </div>
        </el-form-item>
        <!-- -------- -->
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="form.goodsType">
            <el-radio-button label="all">全场通用</el-radio-button>
            <el-radio-button label="chose">指定分类</el-radio-button>
            <el-radio-button label="mall">指定商品</el-radio-button>
          </el-radio-group>

          <!-- 全场通用模块 -->
          <div v-if="form.goodsType === 'all'"></div>

          <!-- 指定分类模块 -->
          <div v-if="form.goodsType === 'chose'" style="margin-top: 10px">
            <el-cascader
              size="mini"
              v-model="form.value"
              :options="optionss1"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              clearable
              @change="asd"
              ref="cascader"
            ></el-cascader
            ><el-button size="mini" @click="addCategory">添加</el-button>
            <el-table
              border
              :data="selectedCategories"
              style="width: 300px; margin-top: 20px"
            >
              <el-table-column label="分类名称" align="center">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template> </el-table-column
              ><el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button size="mini" @click="removeCategory(scope.$index)">
                    删除
                  </el-button></template
                ></el-table-column
              >
            </el-table>
          </div>
          <!-- 指定商品模块 -->
          <div v-if="form.goodsType === 'mall'" style="margin-top: 10px">
            <el-select
              v-model="value"
              size="mini"
              placeholder="请选择"
            >
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.value
                }}</span>
              </el-option> </el-select
            ><el-button size="mini" @click="addgoos(value)">添加</el-button>
            <el-table
              border
              :data="form.goodsValue"
              style="width: 300px; margin-top: 20px"
            >
              <el-table-column label="商品名称" align="center" prop="value">
              </el-table-column>
              <el-table-column label="商品编号" align="center" prop="label">
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="">
                  <el-button size="mini" >
                    删除
                  </el-button></template
                ></el-table-column
              >
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button v-if="flag" type="primary" @click="update">确 定</el-button>
        <el-button v-if="!flag" type="primary" @click="addlist"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  cardList,
  cateList,
  goodList,
  redact,
  carddel,
  add,
  search,
  addssss
} from "@/api/promotion";
import moment from "moment";
export default {
  data() {
    return {
      selectedValue: "", // 用于绑定选中的 value
      selectedLabel: "", // 用于存储选中的 label
      flag: true,
      formLabelWidth: "120px",
      dialogVisible: false,
      form: {
        name: "",
        desc: "",
        tag: "",
        min: 0,
        discount: 0,
        limit: 1,
        status: 0,
        total: 0,
        timeType: 0,
        days: "0",
        goodsType: "all",
        value: [],
        goodsValue: [
          
        ],
        endTime: null,
        startTime: null,
        type: 0,
      },
      validityType: "relativeDays",
      tableData: [],
      tableDate: [],
      tableDato: [],
      formInline: {},
      total: 0,
      imio: "",
      value: [],
      optionss1: [],
      cities: [],
      selectedCategories: [],
      get: {
        page: 1,
        limit: 20,
        sort: "add_time",
        order: "desc",
      },
      got: {},
      gat: {
        limit: 0,
      },
      rules: {
        name: [
          { required: true, message: "优惠券标题不能为空", trigger: "blur" },
        ],
      },
      options1: [
        {
          value: 0,
          label: "通用领券",
        },
        {
          value: 1,
          label: "注册赠券",
        },
        {
          value: 2,
          label: "兑换码",
        },
      ],
      options2: [
        {
          value: 0,
          label: "正常",
        },
        {
          value: 1,
          label: "已过期",
        },
        {
          value: 2,
          label: "已下架",
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      value1: "",
    };
  },
  created() {
    this.getdata();
    this.gotdata();
    this.gatdata();
  },
  methods: {
    getdata() {
      cardList(this.get).then((res) => {
        console.log(res);
        if ((res.data.errmsg = "成功")) {
          this.tableData = res.data.list;
          this.total = res.data.total;
          console.log(this.tableData);
        }
      });
    },
    gotdata() {
      cateList(this.got).then((res) => {
        console.log(res);
        if ((res.data.errmsg = "成功")) {
          this.optionss1 = res.data.list.map((item) => {
            return {
              id: item.id,
              name: item.name,
              children: item.children || [], // 确保 children 存在
            };
          });
          console.log(this.optionss1);
        }
      });
    },
    asd(row, a, b) {
      let nodesInfo = this.$refs["cascader"].getCheckedNodes();
      console.log("nodesInfo>>>>>", nodesInfo[0].pathLabels);
      this.imio = nodesInfo[0].pathLabels[0] + ">" + nodesInfo[0].pathLabels[1];
    },
    addCategory() {
      if (this.form.value.length > 0) {
        this.selectedCategories.push({ name: this.imio });
        // this.form.goodsValue =
      } else {
        this.$message.warning("请先选择一个分类");
      }
    },
    // 添加3
    addgoos(a) {
      console.log(a);
      for( let i = 0; i < this.cities.length; i++) {
        if( this.cities[i].value == a) {
          console.log(this.cities[i]);
          let a = this.cities[i].id
          let b = this.cities[i].label
          this.form.goodsValue.push({ value: a, label: b }) 
      }}
      // console.log(selectedItem)
    },
    gatdata() {
      goodList(this.gat).then((res) => {
        console.log(res);
        if ((res.data.errmsg = "成功")) {
          this.tableDato = res.data.list;
          console.log(res,111111111111111);
          this.cities = res.data.list.map((item) => {
            return {
              value: item.name,
              label: item.goodsSn,
              id: item.id,
            };
          });
          console.log(this.cities);
        }
      });
    },
    // 查询
    onSubmit() {
      this.get.page = 1;
      this.get.name = this.formInline.name;
      this.get.type = this.formInline.type;
      this.get.status = this.formInline.status;
      this.getdata();
    },
    //详情
    mainopen(row) {
      console.log(row);
      this.$router.push({
        name: "cardadd",
        query: {
          tab: "add",
          id: row.id,
          name: row.name,
          desc: row.desc,
          tag: row.tag,
          min: row.min,
          discount: row.discount,
          limit: row.limit,
          goodsType: row.goodsType,
          type: row.type,
          status: row.status,
          startTime: row.startTime,
          updateTime: row.updateTime,
          total: row.total,
        },
      });
    },
    // 编辑
    handleEdit(a, b) {
      this.flag = true;
      this.dialogVisible = true;
      this.form = b;
    },
    close() {
      this.dialogVisible = false;
      this.form = {};
    },
    //编辑确定
    update() {
      redact(this.form).then((res) => {
        if (res.errno == 652) {
          console.log(res);
          this.getdata();
          // this.form = {};
          // this.dialogVisible = false;
          this.$notify.error({
            title: "失败",
            message: "团购已下线",
            // type: "danger",
          });
        }
      });
    },
    // 删除
    dels(a, b) {
      carddel(b).then((res) => {
        if (res.errmsg == "成功") {
          this.getdata();
          this.$notify({
            title: "成功",
            message: "删除优惠券成功",
            type: "success",
          });
        }
      });
    },
    // 添加打开
    addopen() {
      this.flag = false;
      this.dialogVisible = true;
    },
    //添加
    addlist() {
    console.log(this.form);
    if(this.form.goodsType== 'all'){
      this.form.goodsType = 0
    }else if(this.form.goodsType == 'chose'){
      this.form.goodsType = 1
    }else{
      this.form.goodsType = 2
    }
      this.$refs.form.validate((valid) => {
        if (valid) {
          addssss(this.form).then((res) => {
            console.log(res);
            this.getdata();
            this.form = {};
            this.dialogVisible = false;
          });
        } else {
        }
      });
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.get.limit = val;
      this.getdata();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.get.page = val;
      this.getdata();
    },
    formatDate(row, column, cellValue) {
      return moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
    },
    convertStatus1(unitstatus) {
      if (unitstatus === 0) {
        return "全场通用";
      } else if (unitstatus === 1) {
        return "指定分类";
      }
      return "指定商品";
    },
    convertStatus2(unitstatus) {
      if (unitstatus === 0) {
        return "通用领券";
      } else if (unitstatus === 1) {
        return "注册赠券";
      }
      return "兑换码";
    },
    convertStatus3(unitstatus) {
      if (unitstatus === 0) {
        return "正常";
      } else if (unitstatus === 1) {
        return "已过期";
      }
      return "已下架";
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table td,
::v-deep .el-table th {
  padding: 4px 0px;
}
.el-table {
  font-size: 12px;
}
.page {
  margin-top: 40px;
  display: flex;
  justify-content: left;
}
// ::v-deep.el-form-item label {
//   width: 200px;
// }
</style>
